/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.start.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.star.common.CrawlerNewsData;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

/**
 *
 * @author Administrator
 */
public class CrawlerNewsModel {
    private static final String C_NEWS_COLLECTION = "c_news";
    private static final Logger logger = Logger.getLogger(CrawlerNewsModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static CrawlerNewsModel _instance = null;
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public static CrawlerNewsModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new CrawlerNewsModel();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public CrawlerNewsModel() {
        try {
        } catch (Exception ex) {
            logger.error("CrawlerNewsModel: " + ex);
        }
    }
    
    
    public List<CrawlerNewsData> getC_News(int start, int limit) {
        List<CrawlerNewsData> lstC_News = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("published", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(C_NEWS_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);

            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }

            lstC_News = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                //long created = new Double((double) dbObject.get("created")).longValue();  
                long published = (long) dbObject.get("published");
                String site = (String) dbObject.get("site"); 
                String thumbFb = (String) dbObject.get("thumbFb"); 
                String url = (String) dbObject.get("url");
                String images = (String) dbObject.get("images");
                String tags = (String) dbObject.get("tags");
                String author = (String) dbObject.get("author");   
                CrawlerNewsData c_newsData = new CrawlerNewsData(objectId, title, desc, content, published, 
                        site, thumbFb, url, images, tags, author);
                lstC_News.add(c_newsData);
            }
        } catch (Exception ex) {
            logger.error("CrawlerNewsModel.getC_News: " + ex.getMessage(), ex);
        }
        return lstC_News;
    }
    
    
    public List<CrawlerNewsData> getC_News(int start, int limit, String titleSearch, 
            String id_Search, String published_Se, String source_Se) {
        List<CrawlerNewsData> lstC_News = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("published", -1);
            BasicDBObject query = new BasicDBObject();
            if(!titleSearch.equals("")){
                Pattern regex = Pattern.compile(titleSearch, Pattern.CASE_INSENSITIVE); 
                query.put("title", regex);
            }  
            if(!source_Se.equals("")){
                Pattern regex = Pattern.compile(source_Se, Pattern.CASE_INSENSITIVE); 
                query.put("site", regex);
            }            
            if(!id_Search.equals("")){
                query.append("_id", new ObjectId(id_Search));
            }   
                         
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(C_NEWS_COLLECTION);
            DBCursor cursor = coll.find(query).sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstC_News = new ArrayList<>();            
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                //long created = new Double((double) dbObject.get("created")).longValue();  
                long published = (long) dbObject.get("published");
                String site = (String) dbObject.get("site"); 
                String thumbFb = (String) dbObject.get("thumbFb"); 
                String url = (String) dbObject.get("url");
                String images = (String) dbObject.get("images");
                String tags = (String) dbObject.get("tags");
                String author = (String) dbObject.get("author");   
                CrawlerNewsData c_newsData = new CrawlerNewsData(objectId, title, desc, content, published, 
                        site, thumbFb, url, images, tags, author);
                                
                if(!published_Se.equals("")){
                    Date dateCreated = formatter.parse(published_Se);
                    Date d = new Date(published * 1000); 
                    if(d.getDate() != dateCreated.getDate() 
                            || d.getMonth() != dateCreated.getMonth()
                            || d.getYear() != dateCreated.getYear()){
                        continue;
                    }                            
                } 
                lstC_News.add(c_newsData);                
            }
        } catch (Exception ex) {
            logger.error("CrawlerNewsModel.getC_News: " + ex.getMessage(), ex);
        }
        return lstC_News;
    }
    
    
    public CrawlerNewsData getC_NewsById(String id) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(C_NEWS_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String objectId = ((ObjectId) dbObject.get("_id")).toString();
                String title = (String) dbObject.get("title");
                String desc = (String) dbObject.get("desc");
                String content = (String) dbObject.get("content");
                //long created = new Double((double) dbObject.get("created")).longValue();  
                long published = (long) dbObject.get("published");
                String site = (String) dbObject.get("site"); 
                String thumbFb = (String) dbObject.get("thumbFb"); 
                String url = (String) dbObject.get("url");
                String images = (String) dbObject.get("images");
                String tags = (String) dbObject.get("tags");
                String author = (String) dbObject.get("author");   
                CrawlerNewsData c_newsData = new CrawlerNewsData(objectId, title, desc, content, published, 
                        site, thumbFb, url, images, tags, author);                                
                return c_newsData;
            }
        } catch (Exception ex) {
            logger.error("CrawlerNewsModel.getC_NewsById: " + ex.getMessage(), ex);
        }
        return null;
    }
      
    public boolean deleteC_News(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(C_NEWS_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));
            return true;
        } catch (Exception ex) {
            logger.error("CrawlerNewsModel.deleteC_News: " + ex.getMessage(), ex);
        }
        return false;
    }
    
}
